<template>
  <el-form :model="formData" :rules="formDataRules" ref="formData">
    <h2>{{ $t("loginTypeMAC.title") }}</h2>
    <span class="subtitle">{{ $t("loginTypeMAC.subtitle") }}</span>
    <el-form-item label="" prop="telephone" class="margin-top-2">
      <el-input
        class="border-bottom"
        :placeholder="$t('public.placeholder.telephone')"
        prefix-icon="iconfont iconxiugaishoujihaoma-01"
        v-model="formData.telephone"
        maxlength="11"
      ></el-input>
    </el-form-item>
    <el-form-item label="" prop="verifyCode" class="margin-top-2">
      <el-input
        class="border-bottom"
        :placeholder="$t('public.placeholder.verifyCode')"
        prefix-icon="iconfont iconanquanxinxi"
        v-model="formData.verifyCode"
        maxlength="6"
      ></el-input>
      <el-link
        :underline="false"
        type="primary"
        class="btn-getSMS"
        @click="getSMS"
        :disabled="getSmsDisabled"
        >{{ btnText.getSMS }}</el-link
      >
    </el-form-item>
    <el-form-item class="margin-top-2">
      <el-button
        type="primary"
        class="form-control"
        @click="submitForm('formData')"
        >{{ $t("public.login") }}</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import {
  getSms,
  toLoginSms,
  loginSuccess,
  toVerifyGraph,
} from "../../api/login";

export default {
  name: "MAC",
  props: ["operate"],
  watch: {
    operate: {
      handler(val) {
        console.log("change", val);
        if (val.type === "login") {
          this.submitForm("formData");
        }
      },
      deep: true, // 深度监听
      immediate: false, // 初次监听不执行
    },
  },
  created() {
    if (window.TencentCaptcha === undefined) {
      let script = document.createElement("script");
      let head = document.getElementsByTagName("head")[0];
      script.type = "text/javascript";
      script.charset = "UTF-8";
      script.src = "https://ssl.captcha.qq.com/TCaptcha.js";
      head.appendChild(script);
    }
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      let myreg = /^[1][0-9]{10}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t("public.error.telephone")));
      }
      callback();
    };
    return {
      getSmsDisabled: false,
      btnText: {
        getSMS: this.$t("public.getSMS"),
      },
      formData: {
        telephone: "",
        verifyCode: "",
        language: this.$i18n.locale,
      },
      formDataRules: {
        telephone: [{ validator: validatePhone, trigger: "blur" }],
        verifyCode: [
          {
            required: true,
            message: this.$t("public.error.verifyCode"),
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    startLoading() {
      this.$emit("loadingChange", true);
    },
    endLoading() {
      this.$emit("loadingChange", false);
    },
    getSMS() {
      let _this = this;
      _this.$refs["formData"].validateField("telephone", (error) => {
        if (error.length == 0) {
          var captcha = new TencentCaptcha("2082855902", function (res) {
            if (res.ret === 0) {
              // 防水墙验证前端成功
              toVerifyGraph({
                // ipAddr: "string",
                randstr: res.randstr,
                ticket: res.ticket,
              }).then((res) => {
                if (res.status === 200) {
                  getSms({
                    telephone: _this.formData.telephone,
                    smsType: "LOGIN",
                  }).then((res) => {
                    if (res.status === 200) {
                      _this.$message.success(
                        _this.errorCode[_this.$i18n.locale][res.message]
                      );
                      let s = 59,
                        text = _this.$t("public.text");
                      _this.btnText.getSMS = `${s} ${text}`;
                      let timer = setInterval(function () {
                        s--;
                        if (s <= 0) {
                          clearInterval(timer);
                          _this.btnText.getSMS = _this.$t("public.getSMS");
                          _this.getSmsDisabled = false;
                        } else {
                          _this.btnText.getSMS = `${s} ${text}`;
                          _this.getSmsDisabled = true;
                        }
                      }, 1000);
                    } else if (res.status === 9) {
                      _this
                        .$confirm(
                          _this.errorCode[_this.$i18n.locale][res.message],
                          _this.$t("public.message.title"),
                          {
                            confirmButtonText: _this.$t(
                              "public.message.confirmButtonText"
                            ),
                            cancelButtonText: _this.$t(
                              "public.message.cancelButtonText"
                            ),
                          }
                        )
                        .then(() => {
                          _this.$emit("toChangePageType", "Register");
                        })
                        .catch(() => {});
                    } else {
                      _this.$message.error(
                        _this.errorCode[_this.$i18n.locale][res.message]
                      );
                    }
                  });
                } else {
                  _this.$message.error(
                    _this.errorCode[_this.$i18n.locale][res.message]
                  );
                }
              });
            }
          });
          captcha.show(); // 启动防水墙
        } else {
          this.$message.warning(this.$t("public.error.telephone"));
          return false;
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          toLoginSms(this.formData).then((res) => {
            if (res.status === 200) {
              this.$message.success(
                this.errorCode[this.$i18n.locale][res.message]
              );
              loginSuccess(res.data);
            } else {
              this.$message.error(
                this.errorCode[this.$i18n.locale][res.message]
              );
            }
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>